package cn.jhz.learn.community_dynamic.security.handler;

import cn.jhz.learn.community_dynamic.security.manager.JwtManager;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;

import org.jose4j.lang.JoseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Component
public class JwtRefreshSuccessHandler implements AuthenticationSuccessHandler {
    private static final int tokenRefreshInterval = 300;  //刷新间隔5分钟

    private final JwtManager jwtManager;
    
    @Autowired
    public JwtRefreshSuccessHandler(JwtManager jwtManager) {
	super();
	this.jwtManager = jwtManager;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        JwtClaims claims = (JwtClaims) authentication.getCredentials();

        LocalDateTime issueTime = null;
        try {
            issueTime = LocalDateTime.ofInstant(new Date(claims.getIssuedAt().getValueInMillis()).toInstant(), ZoneId.systemDefault());
        } catch (MalformedClaimException e) {
            throw new RuntimeException("格式错误!", e);
            //TODO 定义JWT相关处理
        }
        if(LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime)){
            try {
                //生成token，并把token加密相关信息缓存，具体请看实现类
                RsaJsonWebKey rsaJsonWebKey = jwtManager.newRsaJsonWebKey(((UserDetails)authentication.getPrincipal()).getUsername());
                String token = jwtManager.newInstance(((UserDetails)authentication.getPrincipal()).getUsername(), rsaJsonWebKey);
                jwtManager.clearRsaJsonWebKey(((UserDetails)authentication.getPrincipal()).getUsername());
                jwtManager.rsaJsonWebKey(rsaJsonWebKey, ((UserDetails)authentication.getPrincipal()).getUsername());

                response.setHeader("Authorization", "Bearer " + token);
                response.setCharacterEncoding("UTF-8");
            } catch (JoseException e) {
                e.printStackTrace();
            }
        }else {
            response.setHeader("Authorization", request.getHeader("Authorization"));
            response.setCharacterEncoding("UTF-8");
        }
    }

}
